package com.google.code.p.fop_qrcode;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.fop.util.UnitConv;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.d_project.qrcode.QRCode;

public class QRCode2SVG {

    public static final String SVG_ROOT = "svg";
    
    public String getSvgFromQRCode(QRCode qrcode, int x, int y, int width, int height, int orientation)
            throws IOException {
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        Document document = domImpl.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, SVG_ROOT, null);
        
        int pointWidth = (int)UnitConv.mm2pt(width);
        int pointHeight = (int)UnitConv.mm2pt(height);        
            
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        BufferedImage qrCodeImage = qrcode.createImage(10, 0);
        
        svgGenerator.setSVGCanvasSize(new Dimension(pointWidth, pointHeight));
        svgGenerator.drawImage(qrCodeImage, 0, 0, pointWidth, pointHeight, null);
        
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        Writer out = new OutputStreamWriter(bout, "UTF-8");
        svgGenerator.stream(out, false);
        
        return bout.toString();
    }
    
    public Document getSvgDocumentFromQRCode(QRCode qrcode, int dpi, double length, int cellsize, int margin)
            throws IOException {
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        Document document = domImpl.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, SVG_ROOT, null);

        double pointLength = UnitConv.mm2pt(length);

        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        BufferedImage qrCodeImage = qrcode.createImage(cellsize, margin);
        
        double realLength = (cellsize * qrcode.getModuleCount() + 2 * margin);
        double scale = pointLength / realLength;
        
        svgGenerator.scale(scale, scale);        
        svgGenerator.setSVGCanvasSize(new Dimension((int)pointLength, (int)pointLength));
        svgGenerator.drawImage(qrCodeImage, 0, 0, (int) realLength, (int) realLength, null);

        Element root = document.getDocumentElement();
        svgGenerator.getRoot(root);

        return document;
    }
}
